import { Message, Loading } from 'element-ui';
import XLSX from 'xlsx'

function saveAs(obj, fileName) {
    const tmpa = document.createElement('a');
    tmpa.download = fileName || '下载';
    tmpa.href = URL.createObjectURL(obj); // 绑定a标签
    tmpa.click(); // 模拟点击实现下载
    setTimeout(() => {
        // 延时释放
        URL.revokeObjectURL(obj); // 用URL.revokeObjectURL()来释放这个object URL
    }, 100);
}

function s2ab(s) {
    if (typeof ArrayBuffer !== 'undefined') {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff; // eslint-disable-line
        return buf;
    }
    const buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff; // eslint-disable-line
    return buf;
}

export const outputFile = ({ data, name, tableData, sheetNames, successMsg }) => {
    const loadingInstance = Loading.service({
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
    });
    try {
        const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };
        let wb;
        if (tableData) {
            wb = XLSX.utils.book_new()
            let sheet1 = XLSX.utils.table_to_sheet(tableData)
            let sheet2 = XLSX.utils.json_to_sheet(data)
            XLSX.utils.book_append_sheet(wb, sheet1, sheetNames[0])
            XLSX.utils.book_append_sheet(wb, sheet2, sheetNames[1])
        } else {
            wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }
            wb.Sheets.Sheet1 = XLSX.utils.json_to_sheet(data); // 通过json_to_sheet转成单页(Sheet)数据
        }
        let f = new Blob([s2ab(XLSX.write(wb, wopts))], {
            type: 'application/octet-stream'
        });
        saveAs(f, `${name}.xlsx`);
        loadingInstance && loadingInstance.close();
        Message.success({
            message: successMsg || '导出成功！'
        });
        return data;
    } catch (error) {
        loadingInstance && loadingInstance.close();
        Message.error({
            message: '导出失败！'
        });
    }
};


/**
 * 下载文件
 */
export const downloadFileXDC = () => {

}